package com.olc.railing.camera;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.olc.railing.R;
import com.olc.railing.base.BaseActivity;
import com.olc.railing.busniess.LampControler;
import com.olc.railing.constant.Constants;
import com.olc.railing.model.EventInfo;
import com.olc.railing.utils.ActivityTask;
import com.olc.railing.utils.CameraUtils;
import com.olc.railing.utils.MyLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;


/**
 * @author 郭翰林
 * @date 2019/2/28 0028 16:23
 * 注释:Android自定义相机
 */
public class  CameraActivity extends BaseActivity implements Camera.PreviewCallback, CameraPreview.PreviewCallback,ScanCallback{

    //px30Cmaera相关
    private CameraPreview mPreviewView;
    private CameraScanAnalysis cameraScanAnalysis;
    private static final String TAG = CameraActivity.class.getSimpleName();
    private boolean isHasCamera = false;

    /**
     * 寻卡句柄对象
     **/
    private MyHandler handler = new MyHandler(this);

    private static class MyHandler extends Handler {
        private WeakReference<CameraActivity> cameraActivityWeakReference;

        private MyHandler(CameraActivity cameraActivity) {
            cameraActivityWeakReference = new WeakReference<>(cameraActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }
    @Override
    public int getLayoutResId() {
        return R.layout.activity_camre_layout1;
    }

    @Override
    protected void init() {
        ActivityTask.getInstance().addAty(this);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                isHasCamera = CameraUtils.hasBackFacingCamera();
                MyLog.e(MyLog.TAG, "isHasCamera:" + isHasCamera);
                if (isHasCamera) {
                    mPreviewView = (CameraPreview) findViewById(R.id.capture_preview);
                    mPreviewView.setPreviewCallback(CameraActivity.this);
                    cameraScanAnalysis = new CameraScanAnalysis();
                    cameraScanAnalysis.setScanCallback(CameraActivity.this);
                    startScanUnKnowPermission();
                }else{
                    playMedia(R.raw.ocr_camera_exception);
                }
            }
        },1500);


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            //如果requestCode为100 就走这里
            case 100:
                //permissions[0].equals(Manifest.permission.CAMERA)
                //grantResults[0] == PackageManager.PERMISSION_GRANTED
                //上面的俩个判断可有可无
                if (permissions != null && permissions.length > 0 && permissions[0].equals(Manifest.permission.CAMERA)) {

                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        //如果用户同意了再去打开相机

                    } else {
                        Toast.makeText(CameraActivity.this, "相机权限未授权,应用无法使用", Toast.LENGTH_SHORT).show();
                    }

                } else {
                    startScanWithPermission();
                }
                break;

        }

    }



    /**
     * Do not have permission to request for permission and start scanning.
     */
    protected void startScanUnKnowPermission() {
        MyLog.e(MyLog.TAG, "startScanUnKnowPermission:");
        startScanWithPermission();
    }

    /**
     * There is a camera when the direct scan.
     */
    private void startScanWithPermission() {
        int per = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
        if (per != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 100);
            }
            return;
        }
       boolean isstart =  mPreviewView.start(0);
        if (isstart) {
           // playMedia(new int[]{R.raw.camera_normal},0);
            cameraScanAnalysis.onStart();
        }
    }

    /**
     * Stop scan.
     */
    private void stopScan() {
        isRecogisePlate = false;//保留
        MyLog.d(MyLog.TAG,"stopScan ");
        if(cameraScanAnalysis!=null){
            cameraScanAnalysis.onStop();
        }
        if(mPreviewView!=null){
            mPreviewView.stop();
        }
    }



    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
      //  Log.e(TAG,"onPreviewFrame startScan");
        cameraScanAnalysis.startScan(data, camera);
    }

    @Override
    public void onPreviewStarted(Camera camera) {
        MyLog.e(MyLog.TAG,"onPreviewStarted ");
        camera.setPreviewCallback(this);
    }

    @Override
    public void onScanResult(String plateNo) {
        MyLog.e(MyLog.TAG, "onResult: " + plateNo);
        playMedia(R.raw.chepaishibeichenggong);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopScan();
                LampControler.closeBuguangLamp();//打开补光灯
                isOpenRed = true;//红灯开始闪烁
                ocrVehPlateNo = plateNo;
                EventBus.getDefault().post(new EventInfo(Constants.OCR_VHEPLATE_NO,plateNo));
                finish();
            }
        },1000);

    }


    @Override
    public void endOil() {
        super.endOil();
        playMedia(R.raw.jiayoujieshu);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopScan();
                finish();
            }
        },1500);

    }


}
